// 2021/9/1

const characterEncoding = 'utf8';
// const characterEncoding = 'utf16le';
// const characterEncoding = 'latin1';
// const binaryTextEncoding = 'base64';
// const binaryTextEncoding = 'base64url'; // NodeJS 16
// const binaryTextEncoding = 'hex';

function encodeString(string) {
  const buffer = Buffer.from(string, characterEncoding);
  return buffer.toString(binaryTextEncoding);
}

function decodeString(base64) {
  const buffer = Buffer.from(base64, binaryTextEncoding);
  return buffer.toString(characterEncoding);
}

function allEncodeURI(string) {
  const buffer = Buffer.from(string, 'utf8');
  const hexCode = buffer.toString('hex');

  let byteNumber = '';
  const byteNumbers = [];
  for (let index = 0; index < hexCode.length; index++) {
    if (index % 2 === 0) {
      byteNumber = hexCode[index];
    } else {
      byteNumbers.push(byteNumber + hexCode[index]);
    }
  }

  return '%' + byteNumbers.join('%');
}

// let str = "你好啊";
// let b64 = encodeString(str);
// console.log(b64);
// str = decodeString(b64)
// console.log(str);

let str = "你好，。~ I'm good, now.";
let code = allEncodeURI(str);
//let code = encodeURI(str);
console.log(code);
str = decodeURI(code);
console.log(str);
